package com.renchi.menu.common2.paging;


import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import java.io.Serializable;
import java.util.List;

public class PageJqgrid<T> implements BasePage<T>, Serializable {
    private int page;
    private int pageSize = 10;
    private int total;
    private int records;
    private String sidx;
    private String sord;
    private Result result;
    private List<T> rows;

    public PageJqgrid() {
    }

    public void initResult(Page<T> resultPage) {
        this.setRows(resultPage.getContent());
        this.setRecords((int)resultPage.getTotalElements());
        int totalPage = this.records % this.pageSize == 0 ? this.records / this.pageSize : this.records / this.pageSize + 1;
        this.setTotal(totalPage);
    }

    public void initResult(List<T> rows, int records) {
        this.setRows(rows);
        this.setRecords(records);
        int totalPage = records % this.pageSize == 0 ? records / this.pageSize : records / this.pageSize + 1;
        this.setTotal(totalPage);
    }

    public PageRequest convertToPageRequest() {
        Sort sort = null;
        if (StringUtils.isNotBlank(this.sidx)) {
            if ("desc".equals(this.sord)) {
                sort = new Sort(Direction.DESC, new String[]{this.sidx});
            } else {
                sort = new Sort(Direction.ASC, new String[]{this.sidx});
            }
        }

        return new PageRequest(this.page - 1, this.pageSize, sort);
    }

    public int getPage() {
        return this.page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getPageSize() {
        return this.pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotal() {
        return this.total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getRecords() {
        return this.records;
    }

    public void setRecords(int records) {
        this.records = records;
    }

    public String getSidx() {
        return this.sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return this.sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public List<T> getRows() {
        return this.rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    public Result getResult() {
        return this.result;
    }

    public void setResult(Result result) {
        this.result = result;
    }
}

